package com.gitee.cirnochat.common.event.listener;

import com.gitee.cirnochat.chat.model.vo.resp.ChatSessionStatusResponse;
import com.gitee.cirnochat.common.event.SessionStatusChangeEvent;
import com.gitee.cirnochat.websocket.model.dto.WebSocketUserMessage;
import com.gitee.cirnochat.websocket.service.WebSocketService;
import lombok.RequiredArgsConstructor;
import org.springframework.context.event.EventListener;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import static com.gitee.cirnochat.common.constant.RedisKey.USER_CHAT_CHANNEL_SUBSCRIBE_STATE_KEY;
import static com.gitee.cirnochat.common.constant.WebSocketConstant.SESSION_STATUS_SUBSCRIBE_CHANNEL;

@Component
@RequiredArgsConstructor
public class ChatSessionStatusListener {

    private final StringRedisTemplate redisTemplate;
    private final WebSocketService webSocketService;

    @EventListener(classes = SessionStatusChangeEvent.class)
    public void handleChatSessionStatusChange(SessionStatusChangeEvent event) {
       if (Boolean.TRUE.equals(redisTemplate.hasKey(USER_CHAT_CHANNEL_SUBSCRIBE_STATE_KEY + event.getSessionId()))){
            webSocketService.sendMessageToOnlineDevices(new WebSocketUserMessage(
                    event.getSessionId().toString(),
                    SESSION_STATUS_SUBSCRIBE_CHANNEL,
                    new ChatSessionStatusResponse(event.getTyping(), event.getSessionId())
            ));
        }
    }
}
